package com.ai.bitcoin.service.helper;

import com.ai.bitcoin.jpa.dao.BccOrderDao;
import com.ai.bitcoin.jpa.dao.BccUserDao;
import com.ai.bitcoin.jpa.entity.BccOrder;
import com.ai.bitcoin.jpa.entity.BccSubPackage;
import com.ai.bitcoin.util.JacksonUtils;
import com.ai.bitcoin.weixin.DomManager;
import com.ai.bitcoin.weixin.WeiXinCallBackDom;
import com.ai.bitcoin.weixin.template.SendReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class PayServiceHelper {

    @Autowired
    private BccOrderDao bccOrderDao;

    @Autowired
    private BccUserDao bccUserDao;

    @Autowired
    private WeixinServiceUpdateHelper weixinServiceUpdateHelper;

    @Autowired
    private SendReportService sendReportService;


    public WeiXinPayServiceHelper.WeixinCallBackResult getWeixinCallbackResponseData(HttpServletRequest request) {
        BufferedReader reader = null;

        try {
            reader = request.getReader();
        } catch (IOException e) {
            log.error("get request reader occured error", e);
        }


        String line = "";
        StringBuffer inputString = new StringBuffer();

        try {
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
        } catch (IOException e) {
            log.error("read request input occured error", e);
        }

        String xmlStr = inputString.toString();
        try {
            request.getReader().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!StringUtils.isBlank(xmlStr)) {
            if(log.isDebugEnabled()) {
                log.debug("{} weixin call back request data :" +xmlStr + "{}");
            }
            WeiXinPayServiceHelper.WeixinCallBackResult weixinCallBackResult = DomManager.parseXml(new WeiXinCallBackDom(), xmlStr);
            return weixinCallBackResult;
        }
        else {
            return null;
        }
    }

    @Transactional
    public void updateOrder(Date now, Integer status, String thirdOrderCode, String orderCode, BccOrder order) {
        bccOrderDao.updateOrderByOrderCode(now,status,thirdOrderCode,orderCode);
        BccSubPackage subPackage = JacksonUtils.fromJson(order.getInfo(),BccSubPackage.class);
//        String userSymbol = order.getUserSymbol();
        Double bonus = subPackage.getBonus();
        bccUserDao.updateUserBonusByOpenId(now,bonus,order.getOpenId());
        weixinServiceUpdateHelper.registUserPlcRecord(order.getOpenId(),null,"购买套餐",2,bonus);

//        bccUserDao.updateUserBonus(now,bonus,userSymbol);
    }


}
